package com.rad.ip.discovery.controller;

import com.orbitz.consul.Consul;
import com.orbitz.consul.model.health.Service;
import com.rad.base.model.Result;
import com.rad.ip.discovery.model.IpEntry;
import com.rad.ip.discovery.service.IpEntryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

/**
 * Date:  2018/5/21
 * Time:  14:45
 * Email: siy@hmgsoft.com
 * Created by siy
 */

@RestController
@RequestMapping("/findIp")
public class IpFind {
    private Logger logger = LoggerFactory.getLogger(IpFind.class);
    @Resource
    private IpEntryService ipEntryService;

    @PostMapping("/putAuto")
    public Result putAuto(HttpServletRequest request, String serviceId){
        logger.info("进入获取Ip方法");
        String ip = getIpAddr(request);
        logger.info("获取请求，当前serviceId：{}，地址为：{}",serviceId,ip);
        return ipEntryService.saveIp(serviceId,ip);
    }

    @PostMapping("/find")
    public Result find(String serviceId){
        IpEntry ipEntry = ipEntryService.findById(serviceId);
        return Result.success(ipEntry);
    }

    @PostMapping("/put")
    public Result put(String serviceId,String ipAddress){
        return ipEntryService.saveIp(serviceId,ipAddress);
    }

    @PostMapping("/setAuto")
    public Result set(HttpServletRequest request,String serviceId){
        logger.info("进入获取Ip方法");
        String ip = getIpAddr(request);
        logger.info("获取请求，当前serviceId：{}，地址为：{}",serviceId,ip);
        return ipEntryService.setIp(serviceId,ip);
    }

    @PostMapping("/set")
    public Result set(String serviceId,String ipAddress){
        return ipEntryService.setIp(serviceId,ipAddress);
    }


    private String getIpAddr(HttpServletRequest request){
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

}
